package function

import (
	"reflect"

	"gitee.com/knowgo/ego/core/data"
	"gitee.com/knowgo/ego/egoc"
)

type RequestArg struct {
	arguemntIsRequired bool
	argType            *ArgumentTypeInfo
	pool               ArgumentPool
}

func NewRequestArg(argType *ArgumentTypeInfo, pool ArgumentPool, arguemntIsRequired bool) *RequestArg {
	return &RequestArg{argType: argType, pool: pool, arguemntIsRequired: arguemntIsRequired}
}

// Value 永远返回指针类型的值 ，如果用于非指针参数调用，则需要 .Elem() 返回引用的
func (r *RequestArg) Value(req *data.ServiceRequest, ctx *egoc.Context, argCtx *ArgContext) (reflect.Value, error) {
	var typ = *r.argType
	typ.Required = r.arguemntIsRequired
	val, err := argCtx.ParseRequest(req.Service, req.Argument, &typ, r.pool)
	// 根据参数类型返回值
	var ret reflect.Value
	if r.argType.Ptr || r.argType.Array || r.argType.KeyType != "" {
		ret = val
	} else {
		if val.IsValid() {
			ret = reflect.Indirect(val)
		} else {
			ret = reflect.Zero(typ.TypeInfo.Type)
		}
		// reflect.Zero()
		// if !val.IsZero() && !val.IsNil() {
		// 	ret = val.Elem()
		// }
	}
	return ret, err
}
